package com.tea.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tea.Model.Notice;
import com.tea.Model.dto.NoticeAddDTO;
import com.tea.Model.dto.NoticeUpdateDTO;
import com.tea.mapper.NoticeMapper;
import com.tea.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class NoticeService {
    
    @Resource
    private NoticeMapper noticeMapper;
    
    public Result<List<Notice>> getActiveNotices() {
        List<Notice> notices = noticeMapper.selectActiveNotices();
        return Result.success(notices);
    }
    
    public Result<Page<Notice>> getNoticeList(int current, int size) {
        Page<Notice> page = new Page<>(current, size);
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Notice::getCreateTime);
        
        Page<Notice> result = noticeMapper.selectPage(page, queryWrapper);
        return Result.success(result);
    }
    
    public Result<Notice> getNoticeById(Long id) {
        Notice notice = noticeMapper.selectById(id);
        if (notice == null) {
            return Result.error("通知不存在");
        }
        return Result.success(notice);
    }
    
    public Result<String> addNotice(NoticeAddDTO noticeAddDTO) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeAddDTO, notice);
        notice.setCreateTime(LocalDateTime.now());
        notice.setUpdateTime(LocalDateTime.now());
        
        int result = noticeMapper.insert(notice);
        if (result > 0) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }
    
    public Result<String> updateNotice(NoticeUpdateDTO noticeUpdateDTO) {
        Notice existingNotice = noticeMapper.selectById(noticeUpdateDTO.getId());
        if (existingNotice == null) {
            return Result.error("通知不存在");
        }
        
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateDTO, notice);
        notice.setUpdateTime(LocalDateTime.now());
        
        int result = noticeMapper.updateById(notice);
        if (result > 0) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    
    public Result<String> deleteNotice(Long id) {
        Notice existingNotice = noticeMapper.selectById(id);
        if (existingNotice == null) {
            return Result.error("通知不存在");
        }
        
        int result = noticeMapper.deleteById(id);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
}